package com.icbc.cc.api;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.icbc.cc.security.app.CommonHttpRequest;
import com.icbc.cte.base.CTEConstance;
import com.icbc.cte.logging.Log;
import com.icbc.cte.logging.LogFactory;


public class AppMessageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private static Log log = LogFactory.getCtpLog(AppMessageServlet.class);

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession(); 
		PrintWriter out = response.getWriter();
		String commonURL = CTEConstance.getEnvProperty("msgUrl");//http://sms.datangwealth.com/SMS/SendSMS
		String param = request.getParameter("param");//数字签名与加密过的字符串
		String osFlag = request.getParameter("osFlag");
		
		// 校验数字签名并解密,AES解密
		param = AppCommonUtils.decrypAndSign(param,
				AppCommonUtils.APP_CALL_FLAG, osFlag);//APP_CALL_FLAG=0;osFlag(1是iOS端请求，3是PC端请求)
		
		log.info("AppMessageServlet param:" + param);

		JSONObject obj = (JSONObject) JSONObject.parse(param);
		String mobileNo = (String) obj.get("mobileNo");
		int checkCode = getRandNum(1,999999);
		
		while(checkCode<100000){
			checkCode=getRandNum(1,999999);
		}
		session.setAttribute(mobileNo, Integer.toString(checkCode));
		session.putValue(mobileNo, Integer.toString(checkCode));
		log.info("session mobileNo:" + session.getAttribute(mobileNo));
		

		String sendContext = CTEConstance.getEnvProperty("sendContext");
		String message = "您的验证码为："+checkCode+sendContext;
		String retMsg = CommonHttpRequest.doHttpRequest(commonURL, "POST",
				300000, "userid=d6c0c130-9071-43d5-ac21-7b2409af1eb6&message="
						+ message+ "&mobile=" + mobileNo, "UTF-8");//调用第三方的接口，发送验证码到用户手机号，返回一个状态信息
		
		
		JSONObject reObj = new JSONObject();//将文本解析为jsonObject
		reObj.put("checkCode", checkCode);
		
		JSONObject retObj=JSONObject.parseObject(retMsg);
		
		if(!"1".equals(retObj.get("resultCode"))){
			reObj.put("retCode", "-1");
			reObj.put("retMsg", "通信异常");
			log.info("AppMessageServlet reObj:" + reObj.toJSONString());//将jsonObject序列化为json文本
		}else{
			//将验证码存到表中
			JSONObject checkobj=new JSONObject();
			checkobj.put("phone", mobileNo);
			checkobj.put("checkCode", checkCode);
			String 	result = ApiCommonUtils.excuteOp(checkobj.toString(), "insert_checkcode");
			
			reObj.put("retCode", "0");
			reObj.put("retMsg", "验证码发送成功");
			log.info("AppMessageServlet reObj:" + reObj.toJSONString());//将jsonObject序列化为json文本
		}
		
		
		//生成数字签名，加密并返回
		out.write(AppCommonUtils.encrypAndSign(reObj.toString(), osFlag));
		log.info("session mobileNo:" + session.getAttribute(mobileNo));
		out.flush();
		out.close();
		
	}
	
	public static int getRandNum(int min, int max) {
	    int randNum = min + (int)(Math.random() * ((max - min) + 1));
	    return randNum;
	}

}
